import 'package:film/model/film_model.dart';
import 'package:film/service/api_service.dart';
import 'package:get/get.dart';

class AuthController extends GetxController {
  DioService dioService = new DioService();
  var loginFlag = false.obs;
  Rx<UserInfo> userInfo = UserInfo().obs;

  Future<void> getUserInfo() async {
    ApiResponse<UserInfo?> response = await dioService.getUserInfo();
    if (response.success) {
      userInfo.value = response.data!;
    }
  }

  // 退出登录
  void logout() async {
    DioClient.setAuthToken('');
    loginFlag.value = false;
    userInfo.value = UserInfo();
    userInfo.refresh();
  }

  Future<bool> check() async {
    ApiResponse<UserInfo?> response = await dioService.getUserInfo();
    if (response.code == '000') {
      Get.toNamed('/login');
      return false;
    }
    return true;
  }

  Future<void> checkToken(String routeName, {Map<String, dynamic>? arguments}) async {
    ApiResponse<UserInfo?> response = await dioService.getUserInfo();
    if (response.code == '001') {
      Get.toNamed(routeName, arguments: arguments);
    } else {
      Get.toNamed('/login');
    }
  }

  Future<String> getVideo(String vodId, int index) async {
    var url = '';
    final ApiResponse<VideoDetails> response = await dioService.getVideoByID(vodId: vodId);
    if (response.success && response.data != null) {
      Film film = Film.fromJson(response.data!.video);
      var videoItemList = parseVideoItems(film.vodPlayUrl ?? "");
      if (videoItemList.isNotEmpty) {
        final ApiResponse<String> res = await dioService.getVideoUrl(url: videoItemList[index].code);
        if (res.success) {
          url = res.data ?? '';
        }
      }
    }
    return url;
  }

  List<VideoItem> parseVideoItems(String vodPlayUrl) {
    final List<VideoItem> result = [];
    final episodes = vodPlayUrl.split('#');
    for (var episode in episodes) {
      final parts = episode.split('\$');
      if (parts.length == 2) {
        result.add(VideoItem(
          name: parts[0].trim(),
          code: parts[1].trim(),
        ));
      }
    }
    return result;
  }
}
